package com.txd.mofa.fabu.aty;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.v2.WaitDialog;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.txd.mofa.R;
import com.txd.mofa.base.BaseAty;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.xiangce.ui.EasyPhotosActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Layout(R.layout.paizhao1)
public class PaizhaoAty1 extends BaseAty {

    private static File fileFolder;
    SurfaceView surface;
    ImageView opean;
    Button shan;
    ImageView huan;
    private TextView tv_quxiao;
    private SurfaceHolder holder;//处理画面质量
    private Camera camera;
    private Camera.Parameters parameters;//画面参数
    private boolean isShan=false;
    private List<Integer> mWaitAction = new LinkedList<>(); //暂存拍照的队列
    private boolean isTaking = false;   //是否处于拍照中
    private int iCameraCnt;
    private int  iFontCameraIndex = 1;//后置摄像头
    private int  iBackCameraIndex = 2;//前置摄像头
    private boolean bBack=false;//默认摄像头

    ImageView iv_paizhao;
    TextView ivBack;
    private Bitmap bitmap1,bitmap11;
    private int width,width1;
    private int height,height1;


    private void init() {
        //获取画面的质量
        holder = surface.getHolder();
        //添加回调函数
        holder.addCallback(new MyCallSurface());
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surface.setVisibility(View.VISIBLE);



        gestureDetector = new ScaleGestureDetector(me, new ScaleGestureListener());
    }

    /**
     * 判断是否连续拍照
     */
    public void takePicture() {   //对外暴露的方法，连续拍照时调用
        if (isTaking) {   //判断是否处于拍照，如果正在拍照，则将请求放入缓存队列
            mWaitAction.add(1);
        } else {
            doTakeAction();
        }}

    /**
     * 拍照方法
     */
    private void doTakeAction() {   //拍照方法
        isTaking = true;
        camera.takePicture(null, null, new Ticpic());
    }



    /**
     *   打开闪光灯
     *
     */
    private void getShan() {
        Camera.Parameters parameters = camera.getParameters();
        if(isShan){
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            shan.setText("打开");
            isShan=false;
        }else{
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON);

            shan.setText("关闭");
            isShan=true;
        }
        camera.setParameters(parameters);
    }
    /**
     * 连续拍照时进行处理
     */
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            doTakeAction();
        }
    };

    //读取图片旋转角度
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
//            LogW.out("readPictureDegree : orientation = " + orientation);
            if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                degree = 90;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                degree = 180;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                degree = 270;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 拍照的处理
     *
     */
    class Ticpic implements Camera.PictureCallback {

        @Override
        public void onPictureTaken(byte[] bytes, Camera camera) {

            if (mWaitAction.size() > 0) {
                mWaitAction.remove(0);   //移除队列中的第一条拍照请求，并执行拍照请求
                mHandler.sendEmptyMessage(0);  //主线程中调用拍照
            } else {  //队列中没有拍照请求，走正常流程
                isTaking = false;
            }
            //new SavePictureTask().execute(data);  //异步保存照片
            //camera.startPreview();  //如果不调用 ，则画面不会更新
            if (bytes.length > 0) {
                try {
                    /**
                     * 给图片添加文字水印
                     *
                     */
//                    saveToSDCard(bytes); // 保存图片到sd卡中
//                    Toast.makeText(me, "保存成功", Toast.LENGTH_SHORT).show();

                    //显示图片
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    if (aaa.equals("1")){
                        bitmap1 = rotateBitmap(-90, bitmap);
                        Matrix matrix = new Matrix();
                        //镜子效果
                        matrix.setScale(-1, 1);
                        matrix.postTranslate(bitmap1.getWidth(), 0);
                        bitmap11 = Bitmap.createBitmap(bitmap1, 0, 0, bitmap1.getWidth()
                                , bitmap1.getHeight(), matrix, true);
                    }else if (aaa.equals("2")){
                        bitmap11 = rotateBitmap(90,bitmap);
                    }

                    Intent intent = new Intent(PaizhaoAty1.this,ShenheAty.class);
                    intent.putExtra("filename",saveBitmapFile(bitmap11).getAbsolutePath());
                    intent.putExtra("aa","bb");
                    startActivity(intent);
                    finish();

//                    http(saveBitmapFile(bitmap1));

                    //视图预览实时更新画面
                    camera.cancelAutoFocus(); //这一句很关键
                    //恢复对焦模式
                    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                    parameters.setFocusAreas(null);
//                    camera.setParameters( parameters);
                    //开启预览
                    camera.startPreview();
                    // Camera.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 将拍下来的照片存放在SD卡中
     * @param data
     * @throws IOException
     */
    public void saveToSDCard(byte[] data) throws IOException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        fileFolder = new File(Environment.getExternalStorageDirectory()
                + "/xll/");
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流

        Log.e("filename",jpgFile.getAbsolutePath());

        int i = readPictureDegree(jpgFile.getAbsolutePath());

        //显示图片
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);






    }

    public File saveBitmapFile(Bitmap bitmap){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        fileFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/xll/");
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }

        File jpgFile = new File(fileFolder, filename);

        try {
            FileOutputStream fos = new FileOutputStream(jpgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jpgFile;
    }



    //创建内部类
    class MyCallSurface implements SurfaceHolder.Callback {

        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            getCameraInfo();//取得摄像头
            RequestPermission();

            width = surface.getWidth();
            height = surface.getHeight();
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            width1 = i1;
            height1 = i2;

            //得到画面参数
            parameters = camera.getParameters();

            Camera.Size previewSize = parameters.getPreviewSize();    // 当前 Camera 分辨率

            // 输入当前 CameraView 的长宽，Camera 预览长宽
            setCameraPreviewSize(surface.getWidth(), surface.getHeight(),
                    previewSize.width, previewSize.height);

            parameters.setPictureSize(previewSize.width, previewSize.height);

            parameters.setPictureFormat(PixelFormat.JPEG);

            camera.setParameters(parameters);

            camera.startPreview();

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if (camera != null) {
                camera.release();
                camera = null;
            }

        }
    }



    public void setCameraPreviewSize(int viewWidth, int viewHeight, int cameraWidth, int cameraHeight) {
        boolean bIsPortrait = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);    // 判断水平/垂直状态

        if (bIsPortrait) {
            int tmp = cameraWidth;
            cameraWidth = cameraHeight;
            cameraHeight = tmp;
        }

        int destWidth = viewWidth;
        int destHeight = viewHeight;

        if (bIsPortrait) {
            destHeight = (int)(((double)cameraHeight / cameraWidth) * destWidth);
        } else {
            destWidth = (int)(((double)cameraWidth / cameraHeight) * destHeight);
        }
        Log.e("==========cameraFL",destWidth+"     "+destHeight);
        FrameLayout.LayoutParams cameraFL = new FrameLayout.LayoutParams(cameraWidth, destHeight, Gravity.CENTER); // set size
        cameraFL.setMargins(0, 0, 0, 0);  // set position
        surface.setLayoutParams(cameraFL);
        float i = (float)height / width;
        float i1 = (float)height1 / width1;
        Log.e("===========chicun",i+"");
        Log.e("===========chicun",i1+"");
        Log.e("===========chicun",1+(i-i1)+"");
        surface.setScaleX(1+(i-i1));// 2.1666666667
        surface.setScaleY(1+(i-i1));// 1.7777777778
    }

    //Activity中初始化
    ScaleGestureDetector gestureDetector ;



    //操作类
    class ScaleGestureListener implements ScaleGestureDetector.OnScaleGestureListener {
        float mScaleFactor;

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (detector.getCurrentSpan() > mScaleFactor) {
                zoomOut();
            } else {
                zoomIn();
            }
            mScaleFactor = detector.getCurrentSpan();
            return false;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mScaleFactor = detector.getCurrentSpan();
            //一定要返回true才会进入onScale()这个函数
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            mScaleFactor = detector.getCurrentSpan();
        }
    }

    //自定义相机View中定义方法
    //放大
    public void zoomOut() {
        Camera.Parameters parameters = camera.getParameters();
        if (!parameters.isZoomSupported()) return;

        int zoom = parameters.getZoom() + 1;
        if (zoom < parameters.getMaxZoom()) {
            parameters.setZoom(zoom);
            camera.setParameters(parameters);
        }
    }

    //缩小
    public void zoomIn() {
        Camera.Parameters parameters = camera.getParameters();
        if (!parameters.isZoomSupported()) return;

        int zoom = parameters.getZoom() - 1;
        if (zoom >= 0) {
            parameters.setZoom(zoom);
            camera.setParameters(parameters);
        }
    }

    /**
     * 找出尺寸列表中合适的尺寸。
     */
    private Camera.Size getBestSupportedSize(List<Camera.Size> sizes, int width, int height) {
        Camera.Size bestSize = null;
        for (Camera.Size size : sizes) {
            if (size.width == 640 && size.height == 480) {
                bestSize = size;
                break;
            }
            if (bestSize == null) {
                bestSize = sizes.get(sizes.size() / 2);
            }
        }

        return bestSize;
    }

    private void autoSurfaceSize(Camera.Parameters parameters)    {
        int sH = getResources().getDisplayMetrics().heightPixels;
        int sW = getResources().getDisplayMetrics().widthPixels;
        int pH = parameters.getPreviewSize().width;
        int pW = parameters.getPreviewSize().height;
        float hScale = (float)sH/(float)pH;
        //屏幕高和预览高的比例
        float wScale = (float)sW/(float)pW;
        //屏幕宽和预览宽的比例
        float scale = hScale>wScale?hScale:wScale;
        final ViewGroup.LayoutParams layoutParams = surface.getLayoutParams();
        layoutParams.height = (int) (pH*scale);
        layoutParams.width = (int)(pW*scale);
        surface.post(new Runnable() {
            @Override
            public void run() {
                surface.setLayoutParams(layoutParams);
            }
        });
    }



    private boolean isPreviewActive=false;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        gestureDetector.onTouchEvent(event);

        if(isPreviewActive) {
            //对焦4
            camera.autoFocus(new Camera.AutoFocusCallback() {
                @Override
                public void onAutoFocus(boolean success, Camera camera) {
                    camera.cancelAutoFocus();
                }
            });
        }
        return super.onTouchEvent(event);
    }



    /***
     * 申请权限
     */
    void RequestPermission(){
        if(ContextCompat.checkSelfPermission(me, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(me,new String[]{Manifest.permission.CAMERA},1);
            // Log.d(TAG,"RequestPermission");
        }else{
            initCamera();
        }
    }




    /**
     * 权限回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Log.d(TAG,"onRequestPermissionsResult");
        if(requestCode==1){
            if(grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                initCamera();
                if(camera!=null){
                    camera.startPreview();
                }

            }else{
                Toast.makeText(me,"授权失败",Toast.LENGTH_LONG).show();;
            }
        }
    }

    /**
     * 初始化相机
     */

    private void initCamera(){
        try {
            //打开相机
            camera = Camera.open(iFontCameraIndex);//使用系统硬件打开相机
            bBack=true;
            //设置画面旋转
            camera.setDisplayOrientation(getOrition(me));
            //开启预览
            camera.startPreview();
            isPreviewActive = true;
            camera.setPreviewDisplay(holder);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取摄像头信息
     */

    protected void getCameraInfo(){
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        iCameraCnt = Camera.getNumberOfCameras();

        for (int i = 0; i < iCameraCnt; i++) {
            Camera.getCameraInfo(i,cameraInfo);
            if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
                iFontCameraIndex = i;
            }
            else if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK){
                iBackCameraIndex = i;
            }
        }

    }

    private String aaa = "1";

    /**
     * 点击切换摄像头
     *
     *
     */
    public void onChange() {
        if (camera != null) {
            camera.release();
            camera = null;
        }
        if (bBack == false){
            aaa = "1";
            camera = Camera.open(iFontCameraIndex);
            // Camera.open( Camera.CameraInfo.CAMERA_FACING_FRONT/CAMERA_FACING_BACK);
            try {
                //设置画面旋转
                camera.setDisplayOrientation(getOrition(me));
                //开启预览
                camera.startPreview();
                camera.setPreviewDisplay(holder);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //camera.startPreview();
            bBack = true;
        } else{
            aaa = "2";
            camera = Camera.open(iBackCameraIndex);
            // initCamera();
            try {
                //设置画面旋转
                camera.setDisplayOrientation(getOrition(me));
                //开启预览
                camera.startPreview();
                camera.setPreviewDisplay(holder);
            } catch (IOException e) {
                e.printStackTrace();
            }
            camera.startPreview();
            bBack = false;
        }

    }

    //旋转图片
    public static Bitmap rotateBitmap(int angle, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        Bitmap rotation = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                matrix, true);
        return rotation;
    }

    /**
     * 判断换面的旋转角度
     */
    public int getOrition(Activity activity) {
        int disgre = 0;
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        switch (rotation) {
            case Surface.ROTATION_0:
                disgre = 90;
                break;
            case Surface.ROTATION_90:
                disgre = 0;
                break;
            case Surface.ROTATION_180:
                disgre = 180;
                break;
            case Surface.ROTATION_270:
                disgre = 270;
                break;
        }

        return disgre;
    }


    @Override
    public void initViews() {
        super.initViews();
        surface = findViewById(R.id.surfaceView);
        opean = findViewById(R.id.iv_paizhao);
//        ivBack = findViewById(R.id.tv_quxiao);
        huan = findViewById(R.id.iv_qiehuan);

        tv_quxiao = findViewById(R.id.tv_quxiao);
        init();
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    public void initDatas(JumpParameter paramer) {

    }

    @Override
    public void setEvents() {
        tv_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        opean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkAvailable(PaizhaoAty1.this)) {
                    takePicture();
                }else {
                    Toast.makeText(PaizhaoAty1.this, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }
            }
        });
        huan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onChange();
            }
        });
//        case R.id.iv_paizhao://拍照
//
//        break;
////            case R.id.shan://打开闪光灯
////                getShan();
////                break;
//        case R.id.iv_qiehuan://切换摄像头
//
//        break;
    }
}
